<?php

namespace App\Http\Controllers\Web;

use App\Models\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\CompanyDevelopmentHistory;

class CompanyDevelopmentHistoryController extends Controller
{
    public function index(Request $request)
    {

        $size = $request->input('size', 10);
        $query = CompanyDevelopmentHistory::query();

        $year_start = $request->input("year_start");
        $year_end = $request->input("year_start");

        $query->when($year_start, function ($query) use ($year_start) {
            $query->where('publish_date', ">=", $year_start);
        });
        $query->when($year_end, function ($query) use ($year_end) {
            $query->where('publish_date', "<=", $year_end);
        });

        return $this->successPaginate($query->paginate($size));
    }

    public function requestData(Request $request)
    {
        return $this->validate($request, [
            'year' => 'required',
            'content' => 'required',
            'content_en' => 'nullable',
        ]);
    }

    public function show($id)
    {
        $new = CompanyDevelopmentHistory::query()->findOrFail($id);
        return $this->success($new);
    }

    public function store(Request $request)
    {
        $developmentHistory = new CompanyDevelopmentHistory;
        $this->requestData($request);
        $company = Company::query()->first();
        $companyId = $company->id;
        $year = $request->input("year");
        $content = $request->input("content");
        $content_en = $request->input("content_en");
        $developmentHistory->fill(['year' => $year, 'company_id' => $companyId, 'content' => $content, 'content_en' => $content_en]);
        $developmentHistory->save();
        return $this->success();
    }

    public function update(Request $request, $id)
    {
        $developmentHistory = CompanyDevelopmentHistory::query()->findOrFail($id);
        $requestData = $this->requestData($request);
        $developmentHistory->fill($requestData);
        $developmentHistory->save();
        return $this->success($requestData);
    }

    public function destroy($id)
    {
        $new = CompanyDevelopmentHistory::query()->findOrFail($id);
        $new->delete();
    }
}
